package com.jiyinit.web.core.business.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.jiyinit.web.core.business.enums.OperationTypeConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.business.dto.TaskRequest;
import com.jiyinit.web.core.business.entity.TabCoreTask;
import com.jiyinit.web.core.business.entity.TabCoreUserEntity;
import com.jiyinit.web.core.business.entity.TabCoreUserTask;
import com.jiyinit.web.core.business.service.TaskServiceImpl;
import com.jiyinit.web.core.business.service.UserTaskServiceImpl;
import com.jiyinit.web.core.business.vo.TaskInfoVo;
import com.jiyinit.web.core.business.vo.UserTaskVo;
import com.jiyinit.web.core.common.logic.ParamCheckLogic;
import com.jiyinit.web.core.common.logic.ValidateResult;
import com.jiyinit.web.core.common.util.DateUtil;
import com.jiyinit.web.core.common.util.UserUtil;
import com.jiyinit.web.core.common.vo.CurrentUserVo;

/**
 * 用户管理
 *
 * @author wuyuefeng
 * @version 1.0
 * @date 2017/4/13 9:01
 * @since 1.0
 */
@Controller
@RequestMapping("/task")
public class TaskController {
	/**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
    
    @Resource(name = "core.taskServiceImpl")
    private TaskServiceImpl taskServiceImpl;
    @Resource(name = "core.userTaskServiceImpl")
    private UserTaskServiceImpl userTaskServiceImpl;
    @Resource(name = "core.paramCheckLogic")
    private ParamCheckLogic paramCheckLogic;
    /**
     * 跳转到查询任务信息页面
     *
     * @param request
     * @return
     */
    @RequestMapping("/test")
    public String toFindtest(HttpServletRequest request) {
        return "/task/test";
    }
    /**
     * 跳转到查询任务信息页面
     *
     * @param request
     * @return
     */
    @RequestMapping("/findTasks")
    public String toFindUserList(HttpServletRequest request) {
        return "/task/tasks";
    }
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月3日 上午10:18:37
         * @param 
         * @return
     */
    @RequestMapping("/findMyTasks")
    public String FindMyList(HttpServletRequest request) {
        return "/task/mytasks";
    }
    
    /**
     * 按条件查询用户信息
     *
     * @param request
     * @param taskRequest
     * @return
     */
   
    @RequestMapping(method = RequestMethod.POST, value = "/findByPage")
    @ResponseBody
    public PagingResult<TaskInfoVo> findByPage(HttpServletRequest request, TaskRequest taskRequest) {
    	taskRequest.setLimit(10);
    	taskRequest.setCreateUid(UserUtil.getCurrentUser().getUserId());
        PagingResult<TaskInfoVo> pagingResult = taskServiceImpl.findTasksByCons(taskRequest);
        LogUtil.info(LOGGER, "getTotalRecords:{},getTotalPages:{},getRows:{}", pagingResult.getTotalRecords(), pagingResult.getTotalPages(),pagingResult.getRows());
        return pagingResult;
    }
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月3日 上午10:18:55
         * @param 
         * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/findMyAllTasks")
    @ResponseBody
    public PagingResult<TaskInfoVo> findMyAllTasks(HttpServletRequest request, TaskRequest taskRequest) {
    	taskRequest.setLimit(10);
    	taskRequest.setAlloterId(UserUtil.getCurrentUser().getUserId());
        PagingResult<TaskInfoVo> pagingResult = taskServiceImpl.findMyTasksByCons(taskRequest);
        LogUtil.info(LOGGER, "getTotalRecords:{},getTotalPages:{},getRows:{}", pagingResult.getTotalRecords(), pagingResult.getTotalPages(),pagingResult.getRows());
        return pagingResult;
    }
    
    
    /**
     * 跳到新增页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/add")
    public String add(HttpServletRequest request,TaskRequest taskRequest) {
    	request.setAttribute("taskPid", taskRequest.getTaskId());
    	request.setAttribute("taskPname", taskRequest.getTitle());
    	request.setAttribute("taskPuid", taskRequest.getTaskPuid());
    	
    	Integer userId = UserUtil.getCurrentUser().getUserId();
    	
    	List<UserTaskVo> userTaskVos = new ArrayList<UserTaskVo>();
    	userTaskVos = userTaskServiceImpl.findUserRolls(userId);
    	request.setAttribute("userTaskVos", userTaskVos);
    	
        return "/task/add";
    }
    
    
    /**
     * 新增任务
     *
     * @param request
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/addTask", produces={"application/json; charset=UTF-8"})
    public ResponseEntity<ResponseDto> save(HttpServletRequest request, TaskRequest taskRequest) {
    	
    	Integer alloterId = 0;
    	double plDays = 0.0;
		DateUtil std = new DateUtil();
        // 校验参数
        ValidateResult<TaskRequest> validateResult = paramCheckLogic.checkParamValidate(taskRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }
        
        TabCoreTask tabCoreTask = new TabCoreTask();
        BeanUtils.copyProperties(taskRequest, tabCoreTask);
       
        
        tabCoreTask.setCreateTime(new Date());
        tabCoreTask.setCreateUid(UserUtil.getCurrentUser().getUserId());
        
        Date startTime = tabCoreTask.getStartTimePl();
        Date endTime = tabCoreTask.getEndTimePl();
        try {
        	plDays = (double)std.daysBetween(startTime,endTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
        
        tabCoreTask.setPlDays(plDays+1);
        
        tabCoreTask.setIsDel(new Integer(0));
        //添加分配人
        //alloterId = taskRequest.getAlloterId();
        
        Integer[] userIdss = taskRequest.getAlloterIds();
        
//        TabCoreUserTask tabCoreUserTask = null;
//    	if(userIdss != null&&userIdss.length!=0){
//    		Date alloterEndPl = taskRequest.getAEndPl();
//            String alloterDesc = taskRequest.getADesc();
//            Date alloterStarPl = taskRequest.getAStartPl();
//            tabCoreUserTask = new TabCoreUserTask();
//            tabCoreUserTask.setAlloterId(alloterId);
//            tabCoreUserTask.setStartTimePl(alloterStarPl);
//            tabCoreUserTask.setEndTimePl(alloterEndPl);
//            tabCoreUserTask.setUserTaskDes(alloterDesc);
//            tabCoreUserTask.setCreateTime(new Date());
//    	}
    	int num = 0;
    	if(userIdss != null && userIdss.length!=0){
    		num = taskServiceImpl.addTaskAndUser(tabCoreTask,userIdss,taskRequest, OperationTypeConstant.TASK_ADD);
    	}else{
    		num = taskServiceImpl.addTask(tabCoreTask);
    	}
        
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
    }
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年4月25日 下午5:49:23
         * @param 
         * @return
     */
    @RequestMapping(value = "/update")
    public String taskModify(HttpServletRequest request, Integer taskId) {
    	TabCoreTask tabCoreTask = taskServiceImpl.findTaskById(taskId);
        request.setAttribute("tabCoreTask", tabCoreTask);
        return "/task/edit";
    }
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月3日 下午4:24:49
         * @param 
         * @return
     */
    @RequestMapping(value = "/complete")
    public String taskComplete(HttpServletRequest request, Integer taskId) {
    	TabCoreTask tabCoreTask = taskServiceImpl.findTaskById(taskId);
        request.setAttribute("tabCoreTask", tabCoreTask);
        return "/task/complete";
    }
    
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年4月26日 下午2:43:22
         * @param 
         * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/updateTask")
    public ResponseEntity<ResponseDto> updateTask(HttpServletRequest request, TaskRequest taskRequest) {
        // 校验参数
		double plDays = 0.0;
		DateUtil std = new DateUtil();
		
    	ValidateResult<TaskRequest> validateResult = paramCheckLogic.checkParamValidate(taskRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }
        TabCoreTask tabCoreTask = taskServiceImpl.findTaskById(taskRequest.getTaskId());
        
        String status = tabCoreTask.getStatus();
        
        BeanUtils.copyProperties(taskRequest, tabCoreTask);
        
        if(tabCoreTask.getStatus()==null||tabCoreTask.getStatus().equals("")){
        	tabCoreTask.setStatus(status);
        }

        tabCoreTask.setEditTime(new Date());
        
        if(tabCoreTask.getCreateUid()==null||tabCoreTask.getCreateUid()==0){
        	tabCoreTask.setCreateUid(UserUtil.getCurrentUser().getUserId());
        }
        
        Date startTimeReal = tabCoreTask.getStartTimeReal();
        Date endTimeReal = tabCoreTask.getEndTimeReal();
        double realDays = 0.0;
        if(startTimeReal !=null && endTimeReal !=null){
        	try {
        		realDays = (double)std.daysBetween(startTimeReal,endTimeReal);
    		} catch (ParseException e) {
    			e.printStackTrace();
    		}
        	tabCoreTask.setRealDays(realDays+1);
        }
        Date startTime = tabCoreTask.getStartTimePl();
        Date endTime = tabCoreTask.getEndTimePl();
        try {
        	plDays = (double)std.daysBetween(startTime,endTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
        
        tabCoreTask.setPlDays(plDays+1);
        
        
        tabCoreTask.setIsDel(new Integer(0));

        int num = taskServiceImpl.updateTask(tabCoreTask);
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
    }
    
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年4月26日 下午2:43:35
         * @param 
         * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/delete")
    public ResponseEntity<ResponseDto> delete(HttpServletRequest request,Integer[] taskIds) {
        LogUtil.info(LOGGER, "taskIds:{}", taskIds);
        
        String isOk = taskServiceImpl.deleteTask(taskIds);
        if (null != isOk) {
        	if(isOk.equals("distribute")){
        		return new ResponseEntity<>(ResponseDto.responseFail("该任务已分解，不能删除！"), HttpStatus.OK);
        	}else if(isOk.equals("child")){
        		return new ResponseEntity<>(ResponseDto.responseFail("该任务已分配，不能删除！"), HttpStatus.OK);
        	}else if(isOk.equals("ok")){
        		return new ResponseEntity<>(ResponseDto.responseOK("ok"), HttpStatus.OK);
        	}else{
        		return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
        	}
        }
        return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
    }
    
    
    /**
     * 
         * 跳转任务分配页面
         * @author wuyuefeng
         * @create 2017年4月27日 上午9:35:02
         * @param 
         * @return
     */
    @RequestMapping("/taskAllot")
    public String toTaskAllot() {
        return "/task/taskAllot";
    }
    /**
     * 
         * 任务分配选择人员
         * @author wuyuefeng
         * @create 2017年4月27日 上午9:20:17
         * @param 
         * @return
     */
    
    
    @RequestMapping("/anon/toOrgTree")
    public String toTreeMenu() {
        return "/task/orgTree";
    }
    
    /**
     * 新增任务
     *
     * @param request
     * @param userRequest
     * @return
     */
//    @ResponseBody
//    @RequestMapping(method = RequestMethod.POST, value = "/addTaskUser")
//    public ResponseEntity<ResponseDto> saveTaskUser(HttpServletRequest request, TaskRequest taskRequest) {
//        // 校验参数
//    	Double plDays = 0.0;
//    	DateUtil std = new DateUtil();
//    	 
//        ValidateResult<TaskRequest> validateResult = paramCheckLogic.checkParamValidate(taskRequest);
//        if (!validateResult.isSuccess()) {
//            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
//        }
//        
//        TabCoreTask tabCoreTask = new TabCoreTask();
//        BeanUtils.copyProperties(taskRequest, tabCoreTask);
//      
//        
//        
//        tabCoreTask.setCreateTime(new Date());
//        tabCoreTask.setCreateUid(UserUtil.getCurrentUser().getUserId());
//        Date startTime = tabCoreTask.getStartTimePl();
//        Date endTime = tabCoreTask.getEndTimePl();
//        try {
//        	plDays = (double)std.daysBetween(startTime,endTime);
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}
//        
//        
//
//        int num = taskServiceImpl.addTask(tabCoreTask);
//        if (num > 0) {
//            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
//        }
//        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
//    }
//    
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月4日 下午3:17:06
         * @param 
         * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/anon/checkTitle")
    public ResponseEntity<ResponseDto> checkTitle(HttpServletRequest request,String title) {
        LogUtil.info(LOGGER, "title:{}", title);
        List<TabCoreTask> tabCoreTasks = taskServiceImpl.findTaskByTitle(title);
        if(tabCoreTasks.size() >= 1){
        	return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
            
        }
        return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
    }
    
    
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月12日 上午8:49:48
         * @param 
         * @return
     */
    @RequestMapping("/message")
    public String toTaskMessage(HttpServletRequest request,Integer taskId) {
    	
        return "/task/message";
    }
    
    @RequestMapping("/toTest")
    public String toTest() {
        return "/task/test";
    }
}
